import axios from 'axios'
// 购物车模块
export default {
  namespaced: true,
  state () {
    return {
      list: [] // 放购物车数据
    }
  },
  mutations: {
    // 修改list数据的方法
    updateList (state, val) {
      state.list = val
    },

    // 修改商品的状态
    updateState (state, id) {
      const row = state.list.find(item => item.id == id)
      row.goods_state = !row.goods_state
    },

    // 修改商品的数量
    updateCount (state, obj) {
      const row = state.list.find(item => item.id == obj.id)
      if (obj.value === -1 && row.goods_count === 1) return
      row.goods_count += obj.value
    },

    // 点击全选，控制所有商品是否选中
    changeAllState (state, boo) {
      state.list.forEach(item => {
        item.goods_state = boo
      })
    }
  },
  actions: {
    async initData (store) {
      const { data: res } = await axios.get(
        'http://www.itcbc.com:3006/api/cart'
      )
      // console.log(res) // { status: 200, message: '', list: [......] }
      store.commit('updateList', res.list)
    }
  },
  getters: {
    // 计算已选商品的总数量
    amount (state) {
      const a = state.list.filter(item => item.goods_state)
      // 计算上述商品的总数量
      return a.reduce((t, c) => t + c.goods_count, 0)
    },
    // 计算已选商品的总价格
    total (state) {
      const a = state.list.filter(item => item.goods_state)
      return a.reduce((t, c) => t + c.goods_price * c.goods_count, 0)
    },
    // 计算商品是否都选中了
    isFull (state) {
      // every 意思是每一个
      return state.list.every(item => item.goods_state)
    }
  }
}
